"use strict";
import axios from "axios";
import { Toast } from "tdesign-mobile-vue";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 请求数
let LOADINGCOUNT = 0;
let LOADING;

let config = {
  baseURL: import.meta.env.VITE_APP_API_URL,
  timeout: 10 * 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent

    // 设置loading
    if (LOADINGCOUNT === 0) {
      LOADING = Toast({
        message: "loading...",
        duration: 0,
        theme: "loading",
        preventScrollThrough: true,
      });
    }
    LOADINGCOUNT++;

    let auth = localStorage.getItem("token");
    if (auth) {
      config.headers.AppAuthorization = auth;
    }
    // config.headers.Authorization=localStorage.getItem('token')||''
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    //关闭loading
    LOADINGCOUNT--;
    if (LOADINGCOUNT === 0) {
      LOADING.clear();
    }

    let data= response.data;;

    if (response.status !== 200) {
      setTimeout(() => {
        Toast("网络异常");
      }, 100);
    }

    if (!data) {
      setTimeout(() => {
        Toast("服务器开了个小差");
      }, 100);
    }

    return data;
  },
  function (error) {
    Toast(error.message);
    // Do something with response error
    return Promise.reject(error);
  }
);

/**
 * 导出get请求方法
 * @url 请求地址
 * @params get请求参数
 */
export const get = (url, params) => {
  return _axios.get(url, { params });
};

/**
 * 导出post请求方法
 * @url 请求地址
 * @params post请求参数
 */
export const post = (url, params) => {
  return _axios.post(url, params);
};
